﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalDatabase;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.CacheManage
{
    public partial class SelectComicChapterPage : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false;
        private CacheManageCommon.SelectedStatus selectedStatus = ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.None;
        private int comicId = 0, bookId = 0;
        private string comicSource = string.Empty, comicCoverUrl = string.Empty, comicTitle = string.Empty;

        public SelectComicChapterPage()
        {
            InitializeComponent();
            IsNeedReloadData = true;
        }



        #region ******************************OnNavigatedFrom/OnNavigatedTo******************************
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.IsNeedReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string tmpComicId, tmpBookId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            base.NavigationContext.QueryString.TryGetValue("bookId", out tmpBookId);
            int.TryParse(tmpBookId, out bookId);
            if (comicId <= 0 || bookId <= 0)
            {
                if (base.NavigationService.CanGoBack)
                {
                    base.NavigationService.GoBack();
                }
                return;
            }

            base.NavigationContext.QueryString.TryGetValue("comicSource", out comicSource);
            if (!string.IsNullOrWhiteSpace(comicSource))
                this.txtComicSource.Text = string.Format("来源站点：{0}", comicSource);
            else
                this.txtComicSource.Text = "默认站点";
            base.NavigationContext.QueryString.TryGetValue("comicCoverUrl", out comicCoverUrl);
            base.NavigationContext.QueryString.TryGetValue("comicTitle", out comicTitle);
            this.txtTitle.Text = this.comicTitle;
            if (this.IsNeedReloadData)
            {
                LoadComicChapter(comicId);
            }

            base.OnNavigatedTo(e);
        }
        #endregion ******************************OnNavigatedFrom/OnNavigatedTo******************************


        public void LoadComicChapter(int comicId)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/downloadcomicsview_v3?bookid=", this.bookId.ToString());

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                //无需重新加载数据
                var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(cacheHelper.LocalCacheData);
                if (rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0)
                {
                    BindComicChapter(rootCharacterString.Info.BookPartList);
                }
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {

                        #region ********************获取结果处理********************
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            BindComicChapter(rootCharacterString.Info.BookPartList);
                        }
                        #endregion ********************获取结果处理********************

                    }
                    catch (Exception err)
                    {
                        LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindComicChapter(ObservableCollection<JsonComicChapterInfoBookPartList> itemsource)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (itemsource != null && itemsource.Count > 0)
                {
                    foreach (JsonComicChapterInfoBookPartList item in itemsource)
                    {
                        if (item == null)
                            continue;
                        if (item.PartId <= 0)
                            continue;
                        bool isCached = App.dbContextHelper.IsCachedComicChapterByComicIdAndChapterId(this.comicId, this.bookId, item.PartId);
                        item.IsCachedToolTip = isCached ? "已下载" : "";
                    }
                }
                this.lst.ItemsSource = itemsource;
                this.psbStatus.CloseStatusBar();
            });
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            ListBoxItem lbi = FindParentOfType<ListBoxItem>(cb);        //找到当前CheckBox的所在ListBoxItem
            if (lbi != null)
                lbi.IsSelected = true;
        }

        /// <summary>
        /// 查找父控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FindParentOfType<T>(DependencyObject obj) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);
            while (parent != null)
            {
                if (parent is T)
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {

        }

        private void appBarSort_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;
            this.Dispatcher.BeginInvoke(() =>
            {
                var items = this.lst.ItemsSource as ObservableCollection<JsonComicChapterInfoBookPartList>;
                if (appBarIcon.IconUri.ToString().EndsWith("AscendSort.png"))//从小到大排列
                {
                    appBarIcon.IconUri = new Uri("/Images/Icons/DescSort.png", UriKind.Relative);
                    this.lst.ItemsSource = new ObservableCollection<JsonComicChapterInfoBookPartList>(items.OrderBy(p => p.PartId).ToList<JsonComicChapterInfoBookPartList>());
                }
                else
                {
                    appBarIcon.IconUri = new Uri("/Images/Icons/AscendSort.png", UriKind.Relative);
                    this.lst.ItemsSource = new ObservableCollection<JsonComicChapterInfoBookPartList>(items.OrderByDescending(p => p.PartId).ToList<JsonComicChapterInfoBookPartList>());
                }
                //
                if (this.selectedStatus == ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.All)
                {
                    this.lst.SelectAll();
                }
                else if (this.selectedStatus == ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.UnAll)
                {
                    this.lst.SelectedItems.Clear();
                }
                else
                {

                }
            });
        }

        private void appBarCheck_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("选择全部".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    this.lst.SelectAll();
                    selectedStatus = ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.All;
                }
                else
                {
                    appBarIcon.Text = "选择全部";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    this.lst.SelectedItems.Clear();
                    selectedStatus = ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.UnAll;
                }
            });
        }

        private void appBarDownManage_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.DCVDownloadComicList);
        }

        private void appBarConfirm_Click(object sender, EventArgs e)
        {
            ObservableCollection<LDBComicChapter> chapters = new ObservableCollection<LDBComicChapter>();
            var items = this.lst.SelectedItems;
            if (!(items != null && items.Count > 0))
            {
                return;
            }


            foreach (var item in items)
            {
                var chapter = item as JsonComicChapterInfoBookPartList;
                if (chapter != null)
                {
                    //检测库中是否已存在此章节
                    var comicChapter = App.dbContextHelper.GetOneComicChapter(this.comicId, this.bookId, chapter.PartId);
                    if (comicChapter != null)
                    {
                        continue;
                    }
                    //
                    chapters.Add(new LDBComicChapter()
                    {
                        ComicId = this.comicId,
                        BookId = this.bookId,
                        PartId = chapter.PartId,
                        Name = chapter.Name,
                        Partsize = chapter.Partsize,
                        Partnumber = chapter.Partnumber,
                        Totalpage = chapter.Totalpage,
                        Msourceparturl = chapter.Msourceparturl,
                        Sourceparturl = chapter.Sourceparturl,
                        DownloadStatus = ContentDownloadStatus.等待中.ToString(),
                        ComicIdAndBookIdAndPartId = string.Concat(this.comicId, "#", this.bookId, "#", chapter.PartId)
                    });
                }
            }

            //
            if (chapters.Count() > 0)
            {
                if (MessageBoxResult.OK == MessageBox.Show(string.Format("您共选择了 {0} 章节，确认下载吗？", chapters.Count()), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
                {
                    LDBComic ldbComic = new LDBComic()
                    {
                        ComicId = this.comicId,
                        BookId = this.bookId,
                        ComicIdAndBookId = string.Concat(this.comicId, "#", this.bookId),
                        ComicTitle = this.comicTitle,
                        ComicSourceTitle = this.comicSource,
                        CoverUrl = this.comicCoverUrl,
                        DownloadStatus = ContentDownloadStatus.等待中.ToString()
                    };
                    App.dbContextHelper.InsertComic(ldbComic);
                    App.dbContextHelper.InsertChapter(this.comicId, this.bookId, chapters);
                    //添加或更新收藏夹
                    Task.Run(() =>
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            this.AddOrUpdateBookcase(ldbComic, chapters);
                        });
                    });
                    //跳转至下载漫画列表页
                    NaviService.Navigate(ComicIslandPage.DCVDownloadQueuePage, string.Concat("?comicId=", this.comicId, "&bookId=", this.bookId));
                }
            }
            else
            {
                MessageToastManager.Show("请选择您要下载的漫画章节（已下载则不再下载）！", MessageToastLevel.Warn);
            }
        }

        /// <summary>
        /// 添加或更新收藏夹
        /// <para>添加时需要与服务器交互</para>
        /// </summary>        
        /// <param name="ldbComic"></param>
        /// <param name="chapters"></param>
        void AddOrUpdateBookcase(LDBComic ldbComic, ObservableCollection<LDBComicChapter> chapters)
        {
            if (!(ldbComic != null && chapters != null && chapters.Count > 0 && chapters[0] != null))
            {
                return;
            }
            if (!(ldbComic.ComicId > 0 && ldbComic.BookId > 0 && chapters[0].PartId > 0 && !string.IsNullOrWhiteSpace(ldbComic.ComicTitle) && !string.IsNullOrWhiteSpace(ldbComic.CoverUrl) && !string.IsNullOrWhiteSpace(ldbComic.ComicSourceTitle) && !string.IsNullOrWhiteSpace(chapters[0].Name)))
            {
                return;
            }
            //收藏夹添加或更新
            LocalBookcaseInfoHelper helper = new LocalBookcaseInfoHelper();
            var bookcaseInfo = helper.Get(this.comicId);
            if (bookcaseInfo == null)
            {
                #region 添加
                bookcaseInfo = new LocalBookcaseInfo()
                {
                    ComicId = ldbComic.ComicId,
                    ComicTitle = ldbComic.ComicTitle,
                    Coverurl = ldbComic.CoverUrl,
                    BookId = ldbComic.BookId,
                    SourceName = ldbComic.ComicSourceTitle,
                    PartId = chapters[0].PartId,
                    PartName = chapters[0].Name,
                    IsSync = false,
                    Status = LocalBookcaseStatus.Add.ToString(),
                    LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD)
                };
                if (new LocalBookcaseInfoHelper().Add(bookcaseInfo))
                {
                    //添加收藏则需要发往服务器
                    new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Add, bookcaseInfo);
                }
                #endregion 添加
            }
            else
            {
                #region 更新(无需同步)
                bookcaseInfo.BookId = ldbComic.BookId;
                bookcaseInfo.SourceName = ldbComic.ComicSourceTitle;
                bookcaseInfo.PartId = chapters[0].PartId;
                bookcaseInfo.PartName = chapters[0].Name;
                bookcaseInfo.IsSync = true;
                bookcaseInfo.Status = LocalBookcaseStatus.Update.ToString();
                bookcaseInfo.LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD);
                if (bookcaseInfo.ComicId > 0 || bookcaseInfo.BookId > 0 && bookcaseInfo.PartId > 0)
                {
                    if (new LocalBookcaseInfoHelper().Update(bookcaseInfo))
                    {
                        //更新就不处理了
                        //new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Add, bookcaseInfo);
                    }
                }
                #endregion 更新
            }
        }



        private void lst_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var a = sender as ListBoxItem;
        }

        private void lst_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            //Grid grid = sender as Grid;
            //if (grid == null)
            //    return;

            //var item = grid.DataContext as JsonComicChapterInfoBookPartList;
            //if (item == null)
            //    return;
            //LogHelper.LogInfo("txtCacheStatus:\t" + item.PartId.ToString());
            //foreach (UIElement element in grid.Children)
            //{
            //    if (element == null)
            //        continue;
            //    var txt = element as TextBlock;
            //    if (txt == null)
            //        continue;
            //    if ("txtCacheStatus".Equals(txt.Name))
            //    {
            //        GetDownloadStatusInfo(txt, item.PartId);
            //    }
            //}
        }

    }
}